import socket


def send_msg(udp_socket):
    """sned information"""
    send_data = input("Please enter the data you want send:")
    # use socket transceiver
    # udp_socket.sendto(b'-------hhhhhhh--------', ('192.168.101.18', 9000))

    # get counterpart's(each other's) ip-adder and port
    dest_ip = input("Please enter counterpart's ip:")

    try:
        dest_port = int(input("Please enter each other's port:"))
    except:
        TypeError("Enter numeric type error!")

    udp_socket.sendto(send_data.encode("utf-8"), (dest_ip, dest_port))


def recv_msg(udp_socket):
    """receive information"""
    recv_data = udp_socket.recvfrom(1024)
    recv_msg = recv_data[0]
    send_addr = recv_data[1]
    print("%s:%s" % (str(send_addr), recv_msg.decode('gbk')))


def main():
    # create an udp socket
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    # bind ip and port
    udp_socket.bind("", 7788)
    while True:
        print("-----xxx CHAT ROOM -----")
        print("1:send message")
        print("2:receive message")
        print("0:quit system")
        op = input("Please enter function:")

        if op == "1":
            # send
            send_msg(udp_socket)
        elif op == '2':
            # receive and display
            recv_msg(udp_socket)
        else:
            print("Enter is error, Please enter anew:")
        # send
        send_msg(udp_socket)

        # receive information
        recv_msg(udp_socket)

    # close socket
    udp_socket.close()


if __name__ == "__main__":
    main()
